﻿using Consul;
using M.Core.RmoteCall.Log;
using M.Core.RmoteCall.RpcCall;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Thrift;

namespace M.Core
{
    /// <summary>
    /// 事件管理类
    /// 处理Consul发现新服务时处理的事件,事件由启动时注册

    /// </summary>
    public class ClientEventMgr
    {
        public static ClientEventMgr _consulEventMgr = new ClientEventMgr();
        private ClientEventMgr() { }
        public static ClientEventMgr GetInstance()
        {
            return _consulEventMgr;
        }
        public enum ChangeType
        {
            Add = 0, Remove = 1,
            ReBulidModel = 2,
            Reconn = 3
        }
        public interface IServiceChange
        {
            void Notify(ChangeType changeType, CatalogService catalogService);
        }


        public IList<IServiceChange> OnServiceChangeDelegate = new List<IServiceChange>();


        internal void SendEvent(ChangeType eventType, CatalogService item)
        {
            if (OnServiceChangeDelegate != null && OnServiceChangeDelegate.Count > 0)
            {
                foreach (var sitem in OnServiceChangeDelegate)
                {
                    try
                    {
                        sitem.Notify(eventType, item);
                    }
                    catch (Exception ex)
                    {
                        if (ex is SocketException)
                        {
                            CallLog.GetInstance().Logger(ex, "连接远程Rpc服务器发生错误");
                        }

                    }

                }
            }
        }


      
    }
}
